package io.gitee.chearnee.fw.common.component;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import io.gitee.chearnee.fw.common.model.IBaseEnum;
import io.gitee.chearnee.fw.common.utils.JacksonEnumUtils;
import org.springframework.beans.BeanUtils;

import java.io.IOException;

public final class BaseEnumDeserializer extends StdDeserializer<IBaseEnum<?>> {

    public BaseEnumDeserializer() {
        this(null);
    }

    private BaseEnumDeserializer(Class<IBaseEnum> vc) {
        super(vc);
    }

    @Override
    public IBaseEnum<?> deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException {
        String currentName = p.currentName();
        Object currentValue = p.getCurrentValue();
        Class<?> findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        IBaseEnum<?> fieldCache = JacksonEnumUtils.getFieldCache((Class<? extends IBaseEnum<?>>) findPropertyType, p.getText());
        if (fieldCache != null) {
            return fieldCache;
        }
        if (IBaseEnum.class.isAssignableFrom(findPropertyType) && Enum.class
                .isAssignableFrom(findPropertyType)) {
            Object[] enumConstants = findPropertyType.getEnumConstants();
            for (Object enumConstant : enumConstants) {
                if (enumConstant instanceof IBaseEnum) {
                    if (((IBaseEnum<?>) enumConstant).getValue().toString().equals(p.getText())) {
                        return (IBaseEnum<?>) enumConstant;
                    }
                }
            }
        }
        return null;
    }
}
